import os
from src.modules.media_processor import MediaProcessor
from src.utils.logger import log_info
from .utils import run_ffmpeg

class SubtitleBurner:
    """处理字幕烧录相关功能"""
    
    def __init__(self, startupinfo=None, logger=None):
        self.startupinfo = startupinfo
        self.logger = logger
        self.media_processor = MediaProcessor(startupinfo, logger)
    
    def _color_to_hex(self, color):
        """将常见颜色名称转换为十六进制RGB颜色"""
        color_map = {
            "white": "FFFFFF",
            "black": "000000",
            "red": "FF0000",
            "green": "00FF00",
            "blue": "0000FF",
            "yellow": "FFFF00",
            "cyan": "00FFFF",
            "magenta": "FF00FF"
        }
        
        # 如果是预定义颜色名称
        if color.lower() in color_map:
            return color_map[color.lower()]
        
        # 如果是十六进制颜色代码
        if color.startswith('#') and len(color) in [4, 7]:
            return color[1:]
        
        # 默认返回白色
        return "FFFFFF"
        
    def burn_subtitles_to_video(self, video_path, subtitle_path, output_path=None, 
                              font_size=10, margin_v=25, font_color="white", font_name=None):
        """将字幕烧录到视频中"""
        # 基本文件验证
        if not os.path.exists(video_path):
            return {"success": False, "message": f"视频文件不存在: {video_path}"}
            
        if not os.path.exists(subtitle_path):
            return {"success": False, "message": f"字幕文件不存在: {subtitle_path}"}
        
        # 如果未提供输出路径，生成一个
        if output_path is None:
            file_basename = os.path.basename(video_path)
            name, ext = os.path.splitext(file_basename)
            from tempfile import mkdtemp
            temp_dir = mkdtemp(prefix="subtitle_")
            os.makedirs(temp_dir, exist_ok=True)
            output_path = os.path.join(temp_dir, f"{name}_with_subs{ext}")
        
        try:
            # 确保输出目录存在
            output_dir = os.path.dirname(output_path)
            if output_dir and not os.path.exists(output_dir):
                os.makedirs(output_dir, exist_ok=True)
            
            # 修复字幕路径中的特殊字符
            subtitle_escaped = subtitle_path.replace('\\', '/').replace(':', '\\\\:')
            
            # 构建字体样式
            style = f"FontSize={font_size},MarginV={margin_v}"
            if font_color:
                style += f",PrimaryColour=&H{self._color_to_hex(font_color)}"
            if font_name:
                style += f",FontName={font_name}"
                
            self.media_processor.log_info(f"开始烧录字幕: {os.path.basename(subtitle_path)} -> {os.path.basename(video_path)}")
            self.media_processor.log_info(f"字体样式: {style}")
            
            # 构建命令
            cmd = [
                "ffmpeg",
                "-i", video_path,
                "-vf", f"subtitles={subtitle_escaped}:force_style='{style}'",
                "-c:v", "libx264",
                "-preset", "medium",
                "-crf", "18",
                "-c:a", "copy",  # 保留原始音频
                "-y",
                output_path
            ]
            
            # 执行命令
            result = run_ffmpeg(cmd, "字幕烧录", self.startupinfo, self.logger)
            
            # 检查结果
            if os.path.exists(output_path):
                file_size = os.path.getsize(output_path) / (1024 * 1024)  # MB
                duration = self.media_processor.get_media_duration(output_path)
                
                self.media_processor.log_info(f"字幕烧录成功: {os.path.basename(output_path)}")
                self.media_processor.log_info(f"输出文件大小: {file_size:.2f} MB, 时长: {duration:.2f}秒")
                
                return {
                    "success": True,
                    "message": "字幕烧录成功",
                    "output_path": output_path,
                    "file_size_mb": round(file_size, 2),
                    "duration": duration
                }
            else:
                error_message = "处理完成但输出文件不存在"
                self.media_processor.log_error(error_message)
                return {"success": False, "message": error_message}
                
        except Exception as e:
            error_message = f"烧录字幕时出错: {str(e)}"
            self.media_processor.log_error(error_message)
            import traceback
            self.media_processor.log_error(traceback.format_exc())
            return {"success": False, "message": error_message}